package com.example.usercode.service.service.impl;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.PropertyNamingStrategy;
import com.alibaba.fastjson2.filter.NameFilter;
import com.example.usercode.service.bean.Resp;
import com.example.usercode.service.bean.UserCode;
import com.example.usercode.service.bean.UserTokenVo;
import com.example.usercode.service.mapper.UserCodeMapper;
import com.example.usercode.service.service.IUserCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/4 17:55
 * FileName: UserCodeServiceImpl
 * Description:
 */

@Service
@Slf4j
public class UserCodeServiceImpl implements IUserCodeService {

    @Autowired
    UserCodeMapper userCodeMapper;


    @Autowired
    RestTemplate restTemplate;


    @Autowired
    RedisTemplate<String,String> redisTemplate;
    String tokenUrl="http://localhost:8088/oauth/token";

    String clientId="client";
    String secret="secret";
    String grantType="dingtalk";


    String userNameClientId="client:user:%s:%s";
    @Override
    public UserCode getCode(String userName) {
        return null;
    }

    @Override
    public UserTokenVo getToken(String userName) {

        UserCode userCode = new UserCode();

        String code="";
        String redisKey = String.format(userNameClientId, clientId, userName);
        code = redisTemplate.opsForValue().get(redisKey);
        boolean hasKey=true;
        if(!StringUtils.hasText(code)){
            code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
            userCode.setCode(code);
            userCode.setUserName(userName);
            userCodeMapper.insert(userCode);
            hasKey=false;
        }
        MultiValueMap<String, String> mulmap = new LinkedMultiValueMap<>();
        mulmap.add("client_id", clientId);
        mulmap.add("client_secret", secret);
        mulmap.add("grant_type",grantType);
        mulmap.add("code",code);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ResponseEntity<String> result = null;
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(mulmap, headers);
        ResponseEntity<Resp> postForEntity = restTemplate.postForEntity(tokenUrl, request, Resp.class);
        log.info("postForEntity:{}",postForEntity);
        UserTokenVo userTokenVo = new UserTokenVo();
        if(postForEntity.getStatusCode().equals(HttpStatus.OK)){

             userTokenVo = JSONObject.parseObject(JSONObject.toJSONString(postForEntity.getBody().getData()),UserTokenVo.class, JSONReader.Feature.SupportSmartMatch );
        }

//        if(StringUtils.hasText(userTokenVo.getAccess_token()))
        if(!hasKey){
            redisTemplate.opsForValue().set(String.format(userNameClientId,clientId,userName),code);
        }

        return userTokenVo;
    }
}
